<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <!-- <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" /> -->
    <link rel="stylesheet" type="text/css" href="../css/api.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui.css" />
    <style type="text/css">

    </style>
</head>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #03a9f4;position:fixed;" id="header">
        <a class="aui-pull-left aui-btn" tapmode onclick="closeWin();">
            <span class="aui-iconfont aui-icon-left"></span>
        </a>
        <div class="aui-title" id="title">
            异常发起
        </div>
    </header>
    <div class="aui-content" style="margin-top:50px;">
        <div class="aui-form">
            <div class="aui-input-row" style="display: none;">
                <span class="aui-input-addon" style="width: 20%;text-align: left">异常类型Id</span>
                <input type="text" class='aui-input' style="width: 80%;" id="exceptionTypeGid" value="" />
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">异常类型</span>
                <input type="text" class='aui-input' placeholder="选择异常类型" style="width: 80%;" id="exceptionTypeName" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="selectExceptionType()"></i>
            </div>
            <div class="aui-input-row" style="display: none;">
                <span class="aui-input-addon" style="width: 20%;text-align: left">工作流key</span>
                <input type="text" class='aui-input' style="width: 80%;" id="actModeKey" value="" />
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">工作流</span>
                <input type="text" class='aui-input' placeholder="选择工作流" style="width: 80%;" id="actModeName" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="selectActModeKey()"></i>
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">产线编码</span>
                <input type="text" class="aui-input" placeholder="选择产线" style="width: 80%;" id="lineCode" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectLine()"></i>
            </div>
            <div class="aui-input-row" style="display: none;">
                <span class="aui-input-addon" style="width: 20%;text-align: left">工序id</span>
                <input type="text" class="aui-input" style="width: 80%;" id="opGid" value="" />
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">工位编码</span>
                <input type="text" class="aui-input" placeholder="选择工位" style="width: 80%;" id="opCode" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectOp()"></i>
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">设备编码</span>
                <input type="text" class="aui-input" placeholder="选择设备" style="width: 80%;" id="equipCode" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectEquip()"></i>
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">物料号</span>
                <input type="text" class="aui-input" placeholder="物料号" style="width: 80%;" id="mrlCode" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectMrl()"></i>
            </div>
            <div class="aui-input-row" style="display: none;">
                <span class="aui-input-addon" style="width: 20%;text-align: left">异常内容id</span>
                <input type="text" class="aui-input" style="width: 80%;" id="exceptionContentGid" value="" />
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">异常内容</span>
                <input type="text" class="aui-input" placeholder="选择异常内容" style="width: 80%;" id="exceptionContentName" value="" disabled="true" />
                <i class="aui-input-addon aui-iconfont aui-icon-right" onclick="goSelectExceptionContent()"></i>
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">异常描述</span>
                <input type="text" class="aui-input" placeholder="录入异常描述" style="width: 80%;" id="exceptionRemark" value="" />
            </div>
            <div class="aui-input-row">
                <span class="aui-input-addon" style="width: 20%;text-align: left">备注</span>
                <input type="text" class="aui-input" placeholder="录入备注" style="width: 80%;" id="remark" value="" />
            </div>

            <div class="aui-content" style="background-color: #ffffff">
                <ul class="aui-list-view aui-grid-view" id="imgslist">
                    <li class="aui-list-view-cell aui-img aui-col-xs-4" id="addpic" onclick="imgClick()">
                        <img class="aui-img-object" src="../image/add.jpg">
                    </li>
                </ul>
            </div>
        </div>

        <div class="aui-content aui-content-padded" style="text-align:center;margin-bottom: 5%">
            <p>
                <div class="aui-btn aui-btn-info aui-btn-block" onclick="save()">发起</div>
            </p>
        </div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/hammer.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript">
    //光标所在id
    var idSelector = "";
    var uiMediaScanner = null;
    var imageFilter = null;
    var imageBrowser = null;

    //初始化
    apiready = function() {

        // 引入多选模块
        uiMediaScanner = api.require('UIMediaScanner');
        // 引入过滤压缩模块
        imageFilter = api.require("imageFilter");
        // 引入图片浏览模块
        imageBrowser = api.require('imageBrowser');

    }

    // 获取光标所在组件的id
    function getIdSelector() {
        var e = event || window.event;
        var el = e.srcElement || e.target;
        idSelector = el.id;
        $("#" + el.id).select();
    }

    //选择异常类型
    function selectExceptionType() {
        api.openWin({
            name: 'usmSelectExceptionType',
            url: 'usmSelectExceptionType.html',
            pageParam: {
                name: "usmExceptionBill",
            }
        });
    }

    //异常类型选择后回调函数
    function setExceptionType(exceptionTypeGid, exceptionTypeName) {
        $("#exceptionTypeGid").val(exceptionTypeGid);
        $("#exceptionTypeName").val(exceptionTypeName);
    }

    //选择工作流
    function selectActModeKey() {
        var exceptionTypeGid = $("#exceptionTypeGid").val();
        if (exceptionTypeGid != null && exceptionTypeGid != "" && exceptionTypeGid != undefined) {

            api.openWin({
                name: 'usmSelectActMode',
                url: 'usmSelectActMode.html',
                pageParam: {
                    exceptionTypeGid: exceptionTypeGid,
                    name: "usmExceptionBill",
                }
            });
        } else {
            api.toast({
                msg: '请选择异常类型',
                duration: 3000
            });
        }
    }

    //工作流选择后回调函数
    function setActMode(actModeKey, actModeName) {
        $("#actModeKey").val(actModeKey);
        $("#actModeName").val(actModeName);
    }

    //选择异常内容
    function goSelectExceptionContent() {
        var exceptionTypeGid = $("#exceptionTypeGid").val();
        if (exceptionTypeGid != null && exceptionTypeGid != "" && exceptionTypeGid != undefined) {

            api.openWin({
                name: 'usmSelectExceptionContent',
                url: 'usmSelectExceptionContent.html',
                pageParam: {
                    exceptionTypeGid: exceptionTypeGid,
                    name: "usmExceptionBill",
                }
            });
        } else {
            api.toast({
                msg: '请选择异常类型',
                duration: 3000
            });
        }
    }

    //异常内容选择后回调函数
    function setExceptionContent(exceptionContentGid, exceptionContentName) {
        $("#exceptionContentGid").val(exceptionContentGid);
        $("#exceptionContentName").val(exceptionContentName);
    }

    
    //选择产线
    function goSelectLine() {
        api.openWin({
            name: 'usmSelectLine',
            url: 'usmSelectLine.html',
            pageParam: {
                name: "usmExceptionBill",
            }
        });
    }
    //选择工位
    function goSelectOp() {
        api.openWin({
            name: 'usmSelectCell',
            url: 'usmSelectCell.html',
            pageParam: {
                name: "usmExceptionBill",
                lineCode: document.getElementById("lineCode").value
            }
        });
    }
    //选择设备
    function goSelectEquip() {
        api.openWin({
            name: 'usmSelectEquip',
            url: 'usmSelectEquip.html',
            pageParam: {
                name: "usmExceptionBill",
                cellCode: document.getElementById("opCode").value,
                centerCode: document.getElementById("lineCode").value,
            }
        });
    }

    //产线选择后回调函数
    function setLineCode(lineCode) {
        $("#lineCode").val(lineCode);
        $("#opGid").val("");
        $("#opCode").val("");
        $("#equipCode").val("");
    }
    //工位选择后回调函数
    function setOp(opGid, opCode, opName) {
        $("#opGid").val(opGid);
        $("#opCode").val(opCode);
        $("#equipCode").val("");
    }
    //设备选择后回调函数
    function setEquipCode(equipCode) {
        $("#equipCode").val(equipCode);
    }

    //选择物料
    function goSelectMrl() {
        api.openWin({
            name: 'usmSelectMrl',
            url: 'usmSelectMrl.html',
            pageParam: {
                name: "usmExceptionBill",
            }
        });
    }

    //物料选择后回调函数
    function setMrl(sysid, code, name) {
        $("#mrlCode").val(code);
    }

    //异常发起保存发起
    function save() {

        //获取imgslist中所有的img，保存图片和异常业务记录的关系
        var imgs = document.getElementsByTagName('img');
        var names = [];

        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            //alert(nameStr);
            if ("add.jpg" != nameStr) {
                names[i] = nameStr;
            }
        }

        var picNames = JSON.parse(JSON.stringify(names));
        // console.log("picNames:" + picNames);

        //异常类型
        var exceptionTypeGid = $("#exceptionTypeGid").val();
        //工作流
        var actModeKey = $("#actModeKey").val();
        //异常内容
        var exceptionContentGid = $("#exceptionContentGid").val();
        //异常描述
        var exceptionRemark = $("#exceptionRemark").val();
        //工位id
        var opGid = $("#opGid").val();
        //工位编码
        var opCode = $("#opCode").val();
        //产线编码
        var lineCode = $("#lineCode").val();
        //设备编码
        var equipCode = $("#equipCode").val();
        //物料编码
        var mrlCode = $("#mrlCode").val();
        //备注
        var remark = $("#remark").val();

        //异常类型非空校验
        if (exceptionTypeGid == null || exceptionTypeGid == undefined || exceptionTypeGid == "") {
            api.toast({
                msg: '请选择异常类型',
                duration: 3000
            });
            return;
        }
        //工作流非空校验
        if (actModeKey == null || actModeKey == undefined || actModeKey == "") {
            api.toast({
                msg: '请选择工作流',
                duration: 3000
            });
            return;
        }
        //异常内容非空校验
        if (exceptionContentGid == null || exceptionContentGid == undefined || exceptionContentGid == "") {
            api.toast({
                msg: '请选择异常内容',
                duration: 3000
            });
            return;
        }
        //工序编码非空校验
        if (opCode == null || opCode == undefined || opCode == "") {
            api.toast({
                msg: '请选择工序',
                duration: 3000
            });
            return;
        }

        api.showProgress({
            title: '保存中...',
        });
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/usmExceptionBill";
        var data = {
            values: {
                exceptionTypeGid: exceptionTypeGid,
                exceptionContentGid: exceptionContentGid,
                exceptionRemark: exceptionRemark,
                opGid: opGid,
                opCode: opCode,
                mrlCode: mrlCode,
                remark: remark,
                actModeKey: actModeKey,
                picNames: picNames,
                lineCode : lineCode,
                equipCode : equipCode,
                un: un,
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {

                api.hideProgress();
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == '0') {
                    api.toast({
                        msg: "异常发起成功",
                        duration: 3000
                    });

                    $("#exceptionTypeGid").val("");
                    $("#exceptionTypeName").val("");
                    $("#actModeKey").val("");
                    $("#actModeName").val("");
                    $("#exceptionContentGid").val("");
                    $("#exceptionContentName").val("");
                    $("#exceptionRemark").val("");
                    $("#opGid").val("");
                    $("#opCode").val("");
                    $("#mrlCode").val("");
                    $("#remark").val("");

                    removeImg();



                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                api.hideProgress();
                alert(JSON.stringify(err));
            }
        });
    }

    //保存成功后，清除图片
    function removeImg() {
        var imgs = document.getElementsByTagName('img');
        for (var i = 0; i < imgs.length; i++) {
            var img = imgs[i];
            var srcStr = img.getAttribute('src');
            var obj = $("#imgslist img[src='" + srcStr + "']").parent("li");
            var arrs = srcStr.split('\/');
            var nameStr = arrs[arrs.length - 1];
            if ("add.jpg" != nameStr) {
                $(obj).remove();
            }
        }
    }

    //返回按钮
    function closeWin() {
        api.closeWin({});
    }

    function imgClick() {
        // 获取图片宽高
        var normalW = $("#addpic img").width();

        api.actionSheet({
            title: '选择图片来源',
            buttons: ['照相机', '浏览相册']
        }, function(ret, err) {
            var index = ret.buttonIndex;
            switch (index) {
                // 拍照
                case 1:
                    // 打开拍照
                    api.getPicture({
                        sourceType: "camera",
                        encodingType: "jpg",
                        destinationType: "url",
                        mediaValue: "pic",
                        quality: 50,
                        saveToPhotoAlbum: true
                    }, function(ret, err) {
                        if (ret && ret.data) {
                            // 拍照返回的本地路径
                            var returnUrl = ret.data;
                            // 图片压缩
                            imgCompress(returnUrl, 0.5, 0.5, getExt(returnUrl), function(compressImg) {
                                var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                    "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                // 追加图片
                                $("#addpic").before(showImgHtml);
                                // ########################################  绑定长按事件 ########################
                                addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                //上传图片
                                uploadFile(compressImg);
                            });
                        } else {
                            api.toast({
                                msg: '没有选择，或者选择出错'
                            });
                        }
                    });
                    break;
                    // 打开图片选择器
                case 2:
                    uiMediaScanner.open({
                        type: 'picture',
                        column: 4,
                        classify: true,
                        max: 5,
                        sort: {
                            key: 'time',
                            order: 'desc'
                        },
                        texts: {
                            stateText: '已选*项',
                            cancelText: '取消',
                            finishText: '完成'
                        },
                        styles: {
                            bg: '#fff',
                            mark: {
                                icon: '',
                                position: 'bottom_left',
                                size: 20
                            },
                            nav: {
                                bg: '#b23e4b',
                                stateColor: '#fff',
                                stateSize: 18,
                                cancelBg: 'rgba(0,0,0,0)',
                                cancelColor: '#fff',
                                cancelSize: 18,
                                finishBg: 'rgba(0,0,0,0)',
                                finishColor: '#fff',
                                finishSize: 18
                            }
                        }
                    }, function(ret) {
                        if (ret) {
                            for (var i = 0; i < ret.list.length; i++) {
                                var selectImg = ret.list[i];
                                // 获取图片的路径
                                var selectimgPath = selectImg.path;
                                var selectimgThumbPath = selectImg.thumbPath;
                                // 图片压缩
                                imgCompress(selectimgPath, 0.5, 0.5, selectImg.suffix, function(compressImg) {
                                    var showImgHtml = "<li class='aui-list-view-cell aui-img aui-col-xs-4' onclick='lookImg(\"" + compressImg + "\")'><img class='aui-img-object' src='" + compressImg +
                                        "' style='width:" + normalW + "px;height:" + normalW + "px;'></li>";
                                    // 追加图片
                                    $("#addpic").before(showImgHtml);
                                    // ########################################  绑定长按事件 ########################
                                    addPress($("#imgslist img[src='" + compressImg + "']").parent("li"));

                                    // ################### 上传图片 #########################
                                    uploadFile(compressImg);
                                });
                            }
                        }
                    });
                    break;
            }
        });
    }

    // 为图片添加点击预览功能,排除添加按钮
    function lookImg(compressImg) {
        // 定义一个数组，存储需要预览的图片
        var browerImgs = [];
        // 调用图片预览函数
        browerImgs.push(compressImg);
        openImageBrowser(browerImgs);
    }

    // 图片压缩
    // imgsrc：源图片的路径
    // quality：图片压缩质量，一般建议0.5
    // scale：图片压缩比例，也是建议0.5
    // ext：源图片拓展名
    // callback：转换成功之后回调函数
    function imgCompress(imgsrc, quality, scale, ext, callback) {
        // 压缩文件的保存目录
        var savePath = api.cacheDir + "/" + getNowFormatDate() + "/";
        // 压缩文件生成的随机文件名称
        var savename = NewGuid() + "." + ext;
        imageFilter.compress({
            img: imgsrc,
            quality: quality,
            scale: quality,
            save: {
                album: false,
                imgPath: savePath,
                imgName: savename
            }
        }, function(ret, err) {
            if (ret) {
                callback(savePath + savename);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 打开图片浏览
    // imgs：需要预览的图片集合
    function openImageBrowser(imgs) {
        imageBrowser.openImages({
            imageUrls: imgs,
            showList: false,
            activeIndex: 0
        });
    }

    // 添加长按方法
    function addPress(obj, index) {
        // 获取目前长按的对象
        var hammertime = new Hammer(obj[0]);
        // 绑定长按对象
        hammertime.on("press", function(e) {
            api.confirm({
                title: '温馨提示',
                msg: '您确定要删除该图片吗？',
                buttons: ['确定', '取消']
            }, function(ret, err) {
                if (ret.buttonIndex == 1) {
                    // 移除自己
                    $(obj).remove();
                    api.toast({
                        msg: '删除成功！'
                    });
                }
            });
        });
    }

    // 上传图片
    // url：上传的url地址
    // data：上传的文件
    // callback：上传成功返回地址
    function uploadFile(data) {
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/uploadPhotosAPP";
        var data = {
            values: {
                un: un
            },
            files: {
                file: data
            }
        };
        api.ajax({
            url: url,
            method: 'post',
            dataType: 'json',
            timeout: 300,
            returnAll: false,
            data: data
        }, function(ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == "0") {
                    console.log("上传成功");
                } else if (myobj.code == "1") {
                    alert("上传失败");
                }
            } else {
                alert(JSON.stringify(err));
            }
        });
    }

    // 获取当前的时间，拼接成2015-11-09这样的格式，主要用于对图片进行时间分类
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = year + seperator1 + month + seperator1 + strDate
        return currentdate;
    }

    // 获取文件拓展名
    function getExt(fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }

    // 生成guid,主要用于生成随机文件名
    function NewGuid() {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
</script>

</html>
